import React from 'react'
import { udConfigProvider, UdPage, UdPageHeader, uaaApp, http, routeUtils } from '@/lib'
import { Spin, BackTop } from 'antd'
import classNames from 'classnames'
import { RouteComponentProps } from 'react-router-dom'
import './style.scss'
import apis from '@/apis/SystemSettings'
import udMainStore from '@/store/UdMain'

export default class Index extends React.Component<IProcessManagePageProps, IProcessManagePageState> {
  private webUrls = ['http://10.0.48.27:3338', 'http://10.0.48.28:3338']
  protected pageContainer = udConfigProvider.ui.getPageContainer()
  private processManageIframe
  private PostMessageTypes = {
    /**
     * 获取登录token
     */
    LoginInfo: (params, source, origin) => {
      const searchString = this.props.location.search
      const defaultBrandValue = new URLSearchParams(searchString).get('defaultBrandValue')
      let Authorization = JSON.parse(sessionStorage.getItem('Authorization'))?.accessToken
      let { id } = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile || {}
      //const brandCode = udMainStore.initialBrandValue // 账号只有一个品牌才可进入此页面，传保存的默认品牌
      const brandCode = defaultBrandValue || udMainStore.initialBrandValue // 2021-11-29新增管理员需要看到流程管理
      const organizationId =
        udMainStore.brandList?.find(brand => brand.value === brandCode)?.organizationId ||
        undefined
      let data = { Authorization, id, organizationId, brandCode }
      source.postMessage(data, origin)
    },
    /**
     * 退出
     */
    LoginOut: () => {
      uaaApp.signOut()
    },
  }
  constructor(props) {
    super(props)
    this.state = {
      title: '流程管理',
      subTitle: '',
      querying: false,
      iframeUrl: '', // 流程列表路由地址
    }
    this.processManageIframe = React.createRef()

    //postMessage建立通信
    window.addEventListener('message', this.messageHandler)
  }

  componentWillMount() {
    this.getIframeUrl()
  }

  componentDidMount() {
    if (this.processManageIframe.current) {
      // const iframeWindow = this.processManageIframe.current.contentWindow || this.processManageIframe.current.contentDocument
      // iframeWindow.body.style.backgroundColor="#fff"
      // iframeWindow.location.replace(this.state.iframeUrl)
    }
  }

  componentWillUnmount() {
    //移除事件
    window.removeEventListener('message', this.messageHandler)
  }

  render() {
    const { title, subTitle, querying, iframeUrl } = this.state
    return (
      <UdPage className={classNames('detail-page', 'process-manage-page')}>
        {
          title && <UdPageHeader title={title} subTitle={subTitle}
            onBack={this.onBack}
            affixProps={{ target: () => this.pageContainer }} />
        }
        <Spin style={{minHeight: 400}} spinning={querying}>
          <div className="detail-body">
            {iframeUrl && <iframe
              ref={this.processManageIframe}
              id='process-manage-iframe'
              className='process-manage-iframe'
              src={iframeUrl}
            >当前浏览器不支持iframe，请使用主流浏览器访问</iframe>}
          </div>
        </Spin>
        {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}

      </UdPage>
    )
  }

  public onBack = () => {
    // 内嵌iframe，会先回退iframe的历史
    this.props.history.goBack()
  }

  /** window.message 处理器 */
  private messageHandler = (event) => {
    // const webUrls = this.webUrls
    const origin = event.origin || event.originalEvent.origin
    const source = event.source
    let cmd = event.data
    if (this.PostMessageTypes[cmd.type] == null) {
      return
    }
    if (window == source) {
      return
    }
    /* for (const key in webUrls) {
      let url = webUrls[key]
      if (url == null || url == '') {
        console.error(`${key} 系统未配置 前端访问url。`)
        continue
      }
      if (url.indexOf(origin) === 0) {
        this.PostMessageTypes[cmd.type](cmd.data, source, origin)
        return
      }
    }
    console.error('错误的origion：' + origin, webUrls) */
    this.PostMessageTypes[cmd.type](cmd.data, source, origin)
  }

  public getIframeUrl = () => {
    this.setState({ querying: true })
    http.get(apis.IframeUrl).then(res => {
      const iframeUrl = res.data
      this.setState({
        iframeUrl,
      })
    }).finally(() => this.setState({ querying: false }))
  }
}

interface IProcessManagePageProps extends RouteComponentProps {

}

interface IProcessManagePageState {
  title?: string
  subTitle?: string
  querying?: boolean
  iframeUrl?: string
}